package com.sfc.spiderweb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfc.spiderweb.entity.AmazonTransferInfo;
import com.sfc.spiderweb.entity.AmazonViolationDataInfo;
import com.sfc.spiderweb.entity.PlatformRdpUser;
import com.sfc.spiderweb.entity.po.AmazonScreenshot;
import com.sfc.spiderweb.entity.po.AmazonTransfer;
import com.sfc.spiderweb.entity.po.AmazonViolationData;
import com.sfc.spiderweb.mapper.AmazonTransferMapper;
import com.sfc.spiderweb.mapper.PlatformRdpUserMapper;
import com.sfc.spiderweb.service.AmazonInfoToMysqlService;
import com.sfc.spiderweb.service.AmazonScreenshotService;
import com.sfc.spiderweb.service.AmazonTransferService;
import com.sfc.spiderweb.service.AmazonViolationDataService;
import com.sfc.spiderweb.util.DateUtil;
import com.sfc.spiderweb.util.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@Slf4j
public class AmazonInfoToMysqlServiceImpl extends ServiceImpl<AmazonTransferMapper,AmazonTransfer> implements AmazonInfoToMysqlService   {

    @Value("${ftp.url}")
    private String ftpUrl;
    @Value("${ftp.port}")
    private Integer ftpPort;
    @Value("${ftp.user}")
    private String ftpUser;
    @Value("${ftp.password}")
    private String ftpPassword;

    @Value("${spider.alioss.uploadDir}")
    private String uploadDir;

    @Autowired
    private PlatformRdpUserMapper platformRdpUserMapper;

    @Autowired
    private AmazonTransferMapper amazonTransferMapper;

    @Autowired
    private AmazonTransferService amazonTransferService;

    @Autowired
    private AmazonViolationDataService amazonViolationDataService;

    @Autowired
    private AmazonScreenshotService amazonScreenshotService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void amazonTransfer(String nowDateStr) {
        if (StringUtils.isEmpty(nowDateStr)) {
            nowDateStr = getNowDateStr();
        }
        final String ftpPath = "/financeFtp/amazon_transfer/" + nowDateStr + "/";
        List<AmazonTransfer> transfers = new ArrayList<>();
        QueryWrapper<PlatformRdpUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PlatformRdpUser::getPlatform, "amazon");
        wrapper.lambda().eq(PlatformRdpUser::getState, "1");
        wrapper.lambda().eq(PlatformRdpUser::getStatus, "1");
        List<PlatformRdpUser> list = platformRdpUserMapper.selectList(wrapper);
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        List<String> collect = list.stream().map(x -> x.getPlatformCode().toLowerCase()).collect(Collectors.toList());
        List<FTPUtil.FilePath> filePathList = FTPUtil.getFilePath(ftp, ftpPath);
        List<String> ftpFileName = filePathList.stream().map(FTPUtil.FilePath::getName).collect(Collectors.toList());
        Map<String, String> map = FTPUtil.readFileByfolderInFtp(ftp, ftpPath);
        for (String s : collect) {
            AmazonTransfer amazonTransfer = new AmazonTransfer();
            amazonTransfer.setTransferDate(DateUtil.parse(nowDateStr, "yyyy-MM-dd"));
            String fileName = s + "-TransferInfo-" + nowDateStr + ".txt";
            if (ftpFileName.contains(fileName)) {
                String content = map.get(fileName);

                AmazonTransferInfo amazonTransferInfo = null;
                try {
                    amazonTransferInfo = JSONObject.parseObject(content, AmazonTransferInfo.class);
                } catch (Exception e) {
                    log.error(content + "," + e.getMessage(), e);
                    continue;
                }
                if (!StringUtils.isEmpty(amazonTransferInfo)) {
                    amazonTransfer.setAccount(amazonTransferInfo.getAccount());
                    amazonTransfer.setTransferMessage(amazonTransferInfo.getTransferMessage());
                    amazonTransfer.setCurrentBalanceValue(amazonTransferInfo.getCurrentBalanceValue());
                }
            } else {
                amazonTransfer.setAccount(s);
                amazonTransfer.setTransferMessage("无");
                amazonTransfer.setCurrentBalanceValue("无");

            }
            transfers.add(amazonTransfer);
        }
        QueryWrapper<AmazonTransfer> transferWrapper = new QueryWrapper<>();
        transferWrapper.lambda().eq(AmazonTransfer::getTransferDate, nowDateStr);
        List<AmazonTransfer> queryList = amazonTransferService.list(transferWrapper);
        List<Integer> ids = queryList.stream().map(AmazonTransfer::getId).collect(Collectors.toList());
        amazonTransferService.removeByIds(ids);
        amazonTransferService.saveBatch(transfers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void amazonViolationData(String nowDateStr) {
        if (StringUtils.isEmpty(nowDateStr)) {
            nowDateStr = getNowDateStr();
        }
        List<AmazonViolationData> violationDataList = new ArrayList<>();
        final String ftpPath = "/financeFtp/amazon_violation_data/" + nowDateStr + "/";
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        Map<String, String> map = FTPUtil.readFileByfolderInFtp(ftp, ftpPath);
        for (String key : map.keySet()) {
            String content = map.get(key);
            List<AmazonViolationDataInfo> amazonViolationDataInfos = JSONObject.parseArray(content, AmazonViolationDataInfo.class);
            for (AmazonViolationDataInfo dataInfo : amazonViolationDataInfos) {
                AmazonViolationData violationData = new AmazonViolationData();
                violationData.setAccount(dataInfo.getDownloadFileName());
                violationData.setActionTaken(dataInfo.getActionTaken());
                violationData.setAffected(dataInfo.getAffected());
                violationData.setDownDate(DateUtil.parse(dataInfo.getThisDay(), "yyyy-MM-dd"));
                violationData.setDate(dataInfo.getDate());
                violationData.setNextSteps(dataInfo.getNextSteps());
                violationData.setReason(dataInfo.getReason());
                violationData.setType(dataInfo.getType());
                violationData.setState(Integer.valueOf(dataInfo.getState()));
                violationDataList.add(violationData);
            }
        }
        QueryWrapper<AmazonViolationData> violationDataQueryWrapper = new QueryWrapper<>();
        violationDataQueryWrapper.lambda().eq(AmazonViolationData::getDownDate, nowDateStr);
        List<AmazonViolationData> queryList = amazonViolationDataService.list(violationDataQueryWrapper);
        List<Integer> ids = queryList.stream().map(AmazonViolationData::getId).collect(Collectors.toList());
        amazonViolationDataService.removeByIds(ids);
        amazonViolationDataService.saveBatch(violationDataList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void amazonIndexScreenshot(String nowDateStr) {
        if (StringUtils.isEmpty(nowDateStr)) {
            nowDateStr = getNowDateStr();
        }
        List<AmazonScreenshot> screenshots = new ArrayList<>();
        final String ftpPath = "/financeFtp/amazon_index_screenshot/" + nowDateStr + "/";
        log.info("读ftp文件");
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        List<FTPFile> ftpFiles = FTPUtil.readFileName(ftp, ftpPath);
        for (FTPFile file : ftpFiles) {
            String fileName = file.getName();
            AmazonScreenshot amazonScreenshot = new AmazonScreenshot();
            String account = fileName.substring(0, fileName.indexOf("_"));
            String screenshotTime = fileName.substring(fileName.indexOf("_") + 1, fileName.lastIndexOf("."));
            amazonScreenshot.setAccount(account);
            amazonScreenshot.setScreenshotDate(DateUtil.parse(nowDateStr, "yyyy-MM-dd"));
            amazonScreenshot.setScreenshotTime(DateUtil.parse(screenshotTime, "yyyyMMddHHmmss"));
            amazonScreenshot.setScreenshotUrl(ftpPath + fileName);
            screenshots.add(amazonScreenshot);
            //上传oss
            //OssUtil.uploadFileToOss(file,uploadDir+nowDateStr+"/"+fileName);
        }
        QueryWrapper<AmazonScreenshot> screenshotQueryWrapper = new QueryWrapper<>();
        screenshotQueryWrapper.lambda().eq(AmazonScreenshot::getScreenshotDate, nowDateStr);
        List<AmazonScreenshot> queryList = amazonScreenshotService.list(screenshotQueryWrapper);
        List<Integer> ids = queryList.stream().map(AmazonScreenshot::getId).collect(Collectors.toList());
        amazonScreenshotService.removeByIds(ids);
        amazonScreenshotService.saveBatch(screenshots);
    }

    private String getNowDateStr() {
        String dateStr = DateUtil.getNetTime();
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
        return DateUtil.formatDate("yyyy-MM-dd", date);
    }
}
